package com.wt.test.jdbc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.transaction.annotation.Transactional;

import javax.sql.DataSource;
import java.sql.Types;
import java.util.List;

/**
 * @description
 * @author: wangtao
 * @date:15:50 2019/5/28
 * @email:taow02@jumei.com
 */
public class UserServiceImpl implements UserService {

	private JdbcTemplate jdbcTemplate;

	public UserServiceImpl setDatasource(DataSource datasource) {
		this.jdbcTemplate = new JdbcTemplate(datasource);
		return this;
	}

	@Override
	public void save(UserEntity user) {
		Object[] args = {user.getName(), user.getAge(), user.getSex()};
		jdbcTemplate.update("insert into `person`(`name`,`age`,`sex`) values(?,?,?)",
				args,
				new int[]{Types.VARCHAR, Types.VARCHAR, Types.VARCHAR});
	}

	@Override
	public List<UserEntity> getUsers() {
		return jdbcTemplate.query("select * from person",
				(set, index) -> new UserEntity(set.getString("name"), set.getString("age"),
						set.getString("sex")));
	}

	@Override
	@Transactional
	public void saveException(UserEntity user) throws Exception {
		Object[] args = {user.getName(), user.getAge(), user.getSex()};
		jdbcTemplate.update("insert into `person`(`name`,`age`,`sex`) values(?,?,?)",
				args,
				new int[]{Types.VARCHAR, Types.VARCHAR, Types.VARCHAR});
		throw new RuntimeException("error");
//		throw new Exception("error");
	}

}
